import sys
import PySimpleGUI as sg
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO
from faker import Faker
from pathlib import Path


def resource_path(relative_path):
    """ 获取资源的绝对路径。在开发环境中返回相对路径，在打包后的环境中返回绝对路径。"""
    try:
        # PyInstaller 创建的临时文件夹
        base_path = Path(sys._MEIPASS)
    except Exception:
        # 没有打包的环境（例如，正常运行 Python 脚本）
        base_path = Path(__file__).parent.resolve()

    return base_path / relative_path

# 更新资源文件路径
background_image_path = resource_path('resources/front_template.png')
font_path = resource_path('resources/AlibabaPuHuiTi-3-55-Regular.ttf')

fake = Faker('ZH_CN')
CHAR_SPACING = 4


# 随机生成身份证号码（这里使用简单的示例，实际情况应遵循身份证号码生成规则）
def gen_fake_data():
    """
    姓名，年月日，身份证号码
    :return:
    """
    name = fake.name()
    id_number = fake.ssn()
    birth_year, birth_month, birth_day = id_number[6:10], id_number[10:12], id_number[12:14]

    data = {
        'name': '  '.join(name) if len(name) == 2 else name,
        'birth_year': birth_year,
        'birth_month': birth_month,
        'birth_day': birth_day,
        'id_number': id_number,
    }
    return data


def create_id_card_image(info, background_image_path, font_path):
    """
    将身份证号码添加到背景图片上，并返回图片对象
    """
    image = Image.open(background_image_path)
    draw = ImageDraw.Draw(image)
    font = ImageFont.truetype(str(font_path), size=16)

    # 姓名
    draw.text((155, 84), info.get('name', '老佛爷'), font=font, fill="black")

    # 出生年月日
    draw.text((160, 154), info.get('birth_year', '0'*4), font=font, fill="black")
    draw.text((225, 154), info.get('birth_month', '0'*2), font=font, fill="black")
    draw.text((265, 154), info.get('birth_day', '0'*2), font=font, fill="black")

    # 身份证号码
    id_number = info.get('id_number', '0'*18)
    x_pos, y_pos = 220, 280
    for char in id_number:
        draw.text((x_pos, y_pos), char, font=font, fill="black")
        char_w_h, *_ = font.font.getsize(char)
        x_pos += char_w_h[0] + CHAR_SPACING

    return image


id_card_image = create_id_card_image(gen_fake_data(), background_image_path, font_path)
bio = BytesIO()
id_card_image.save(bio, format="PNG")
button_layout = [[sg.Button("重新生成")]]
layout = [
    [sg.Image(data=bio.getvalue(), key='ID_IMAGE')],
    [sg.Column(button_layout, element_justification='center', expand_x=True)]  # 居中按钮
]

# 创建窗口
window = sg.Window("身份证测试数据生成器（仅供OCR识别验证用途）", layout)

# 事件循环
while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED:
        break
    if event == "重新生成":
        # 更新身份证图片
        id_card_image = create_id_card_image(gen_fake_data(), background_image_path, font_path)
        bio = BytesIO()
        id_card_image.save(bio, format="PNG")
        window['ID_IMAGE'].update(data=bio.getvalue())

# 关闭窗口
window.close()